import React, { useState, useEffect, useRef } from 'react';
import { TextField, Box, Dialog, Button, DialogTitle, DialogContent, DialogContentText, DialogActions, MenuItem } from '@mui/material';
import Utils from '../../../utils/Utils';
import Select from '../../general/Select';
import NetPyNEField from '../../general/NetPyNEField';
import NetPyNETextField from '../../general/NetPyNETextField';
import ListComponent from '../../general/List';
import SelectField from '../../general/SelectField';

interface NetPyNEStimulationSourceProps {
  name: string;
  renameHandler?: (newName: string) => boolean;
  updateCards?: () => void;
  [key: string]: any;
}

const STIM_SOURCE_TYPE_OPTIONS = [
  { type: 'NetStim' },
  { type: 'IClamp' },
  { type: 'VClamp' },
  { type: 'SEClamp' },
  { type: 'AlphaSynapse' },
];

/**
 * NetPyNEStimulationSource Component
 * Placeholder implementation - full functionality to be migrated
 */
const NetPyNEStimulationSource: React.FC<NetPyNEStimulationSourceProps> = ({
  name,
  renameHandler,
  updateCards,
  ...otherProps
}) => {
  const [currentName, setCurrentName] = useState(name);
  const [sourceType, setSourceType] = useState<string>('NetStim');
  const [errorMessage, setErrorMessage] = useState<string | undefined>(undefined);
  const [errorDetails, setErrorDetails] = useState<string | undefined>(undefined);
  const renamingRef = useRef(false);
  const updateTimerRef = useRef<NodeJS.Timeout | undefined>(undefined);

  useEffect(() => {
    updateLayout();
  }, []);

  useEffect(() => {
    if (currentName !== name) {
      Utils.evalPythonMessage(
        `netpyne_geppetto.netParams.stimSourceParams['${name}']['type']`,
        []
      ).then((response: string) => {
        if (response !== sourceType) {
          setSourceType(response);
          if (updateCards) {
            updateCards();
          }
        }
      });
      setCurrentName(name);
      setSourceType('');
    }
  }, [name]);

  const updateLayout = (): void => {
    const opts = STIM_SOURCE_TYPE_OPTIONS.map((option) => option.type);
    Utils.evalPythonMessage(
      `[value == netpyne_geppetto.netParams.stimSourceParams['${currentName}']['type'] for value in ${JSON.stringify(opts)}]`,
      []
    ).then((responses: boolean[]) => {
      if (Array.isArray(responses)) {
        responses.forEach((response, index) => {
          if (response && sourceType !== opts[index]) {
            setSourceType(opts[index]);
            if (updateCards) {
              updateCards();
            }
          }
        });
      }
    });
  };

  const handleRenameChange = (event: React.ChangeEvent<HTMLInputElement>): void => {
    const storedValue = name;
    const newValue = Utils.nameValidation(event.target.value);
    
    if (renameHandler) {
      const updateCondition = renameHandler(newValue);
      const triggerCondition = Utils.handleUpdate(
        updateCondition,
        newValue,
        event.target.value,
        { 
          setState: (updater: any) => {
            if (typeof updater === 'function') {
              // Handle function updater if needed
            } else {
              setErrorMessage(updater.errorMessage);
              setErrorDetails(updater.errorDetails);
            }
          }
        },
        'StimulationSource'
      );

      if (triggerCondition) {
        triggerUpdate(() => {
          Utils.renameKey(
            'netParams.stimSourceParams',
            storedValue,
            newValue,
            (response: any, newVal: string) => {
              renamingRef.current = false;
              if (updateCards) {
                updateCards();
              }
            }
          );
          renamingRef.current = true;
          updateLayout();
        });
      }
    }
  };

  const triggerUpdate = (updateMethod: () => void): void => {
    if (updateTimerRef.current !== undefined) {
      clearTimeout(updateTimerRef.current);
    }
    updateTimerRef.current = setTimeout(updateMethod, 1000);
  };

  const handleStimSourceTypeChange = (event: any, child: React.ReactNode): void => {
    const value = event.target.value as string;
    Utils.execPythonMessage(
      `netpyne_geppetto.netParams.stimSourceParams['${currentName}']['type'] = '${value}'`
    );
    setSourceType(value);
    if (updateCards) {
      updateCards();
    }
  };

  const dialogPop = errorMessage !== undefined ? (
    <Dialog open style={{ whiteSpace: 'pre-wrap' }}>
      <DialogTitle>{errorMessage}</DialogTitle>
      <DialogContent style={{ overflow: 'auto' }}>
        <DialogContentText>{errorDetails}</DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button
          variant="contained"
          color="primary"
          onClick={() => {
            setErrorMessage(undefined);
            setErrorDetails(undefined);
          }}
        >
          BACK
        </Button>
      </DialogActions>
    </Dialog>
  ) : null;

  return (
    <Box className="scrollbar scrollchild" mt={1}>
      <Box mb={1}>
        <TextField
          fullWidth
          variant="filled"
          onChange={handleRenameChange}
          value={currentName}
          disabled={renamingRef.current}
          label="The name of the stimulation source"
        />
      </Box>

      <NetPyNEField id="netParams.stimSourceParams.type" mb={3}>
        <Select
          id="stimSourceTypeSelect"
          value={sourceType}
          onChange={handleStimSourceTypeChange}
          label="Stimulation Source Type"
        >
          {STIM_SOURCE_TYPE_OPTIONS.map((option) => (
            <MenuItem key={option.type} value={option.type}>
              {option.type}
            </MenuItem>
          ))}
        </Select>
      </NetPyNEField>

      {/* Additional fields based on sourceType will be added here as the full component is migrated */}
      <Box mt={2}>
        <NetPyNEField id={`netParams.stimSourceParams.${name}.rate`}>
          <NetPyNETextField
            fullWidth
            variant="filled"
            model={`netParams.stimSourceParams['${name}']['rate']`}
          />
        </NetPyNEField>
      </Box>

      {dialogPop}
    </Box>
  );
};

export default NetPyNEStimulationSource;

